package xyz.bali16.module.mute.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.starblues.annotation.Supplier;
import com.google.common.base.Preconditions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import xyz.bali16.application.core.utils.TimeUtil;
import xyz.bali16.module.mute.entity.Mute;
import xyz.bali16.module.mute.mapper.MuteMapper;
import xyz.bali16.module.mute.model.MuteAddParam;
import xyz.bali16.module.mute.model.MutePageParam;
import xyz.bali16.module.mute.model.MuteUpdateParam;

import java.text.ParseException;
import java.util.Date;

import static xyz.bali16.application.core.utils.TimeUtil.FORMAT_SECONDS;


/**
 * @author bali2 on 9/3/2023.
 * @version 1.0
 */
@Service
@Supplier("mute")
public class MuteServiceImpl extends ServiceImpl<MuteMapper, Mute> implements MuteService {
    private final MuteMapper muteMapper;

    public MuteServiceImpl(MuteMapper muteMapper) {
        this.muteMapper = muteMapper;
    }

    @Override
    public IPage<Mute> getPage(MutePageParam param) {
        IPage<?> page = new Page<>(param.getCurrent(), param.getSize());
        return this.baseMapper.getPage(page, param.getUserId());
    }

    @Override
    public void addMute(MuteAddParam param) throws Exception {
        Preconditions.checkNotNull(param, "MuteAddParam 参数不能为为空");
        Mute mute = new Mute();
        BeanUtils.copyProperties(param, mute);
        System.out.println(mute);
        save(mute);
    }

    @Override
    public void updateMute(MuteUpdateParam param) throws Exception {
        Preconditions.checkNotNull(param, "MuteAddParam 参数不能为为空");
        Mute mute = new Mute();
        BeanUtils.copyProperties(param, mute);
        updateById(mute);
    }


    @Override
    public void delete(String muteId) throws Exception {
        if (muteId == null) {
            return;
        }
        removeById(muteId);
    }

    @Override
    @Supplier.Method("isMute")
    public boolean isMute(String userId) throws ParseException {
        Mute mute = this.getById(userId);
        if (mute != null) {
            Date mute_date = TimeUtil.getDateByString(mute.getGmtUpdated(), FORMAT_SECONDS);
            // 到达禁言日期
            if (mute_date.before(new Date()) || mute_date.equals(new Date())) {
                removeById(mute.getId());// 解除禁言
                return false;
            }
            return true;
        }
        return false;
    }
}
